import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gt_flutter_admin/app/routes.dart';
import 'package:gt_flutter_admin/services/api_service.dart';
import 'package:gt_flutter_admin/utils/toast_utils.dart';

import '../../../models/page.dart' as gt_page;
import '../../../models/role.dart';

class RoleUpdateController extends GetxController {
  // 数据
  final Rx<gt_page.Page> menuPage = gt_page.Page().obs;

  final RxBool isEdit = true.obs;

  // 选择控件
  final List<num> menuIds = [];
  final RxString menuNames = ''.obs;

  // 文本控件
  TextEditingController roleNameText = TextEditingController();
  TextEditingController remarkText = TextEditingController();

  @override
  void onInit() async {
    super.onInit();

    // 初始化菜单选项列表
    menuPage.value = await listMenu();

    Role? role = Get.rootDelegate.arguments();
    if (role != null) {
      isEdit.value = false;

      roleNameText.text = role.roleName;
      remarkText.text = role.remark;

      menuIds.addAll(List<num>.from(role.menuIds));
      menuNames.value = role.menuNames.join(" ");
    }
  }

  /// 提交表单
  void onSubmit() async {
    Map<String, dynamic> data = {
      'menuIds': menuIds,
      'remark': remarkText.text,
      'roleName': roleNameText.text,
    };

    Role? role = Get.rootDelegate.arguments();
    if (role == null) {
      await createRole(data).then((value) => ToastUtils.success('新增成功'));
    } else {
      data['id'] = role.id;
      await updateRole(data).then((value) => ToastUtils.success('编辑成功'));
    }

    Get.rootDelegate.toNamed(Routes.ROLE);
  }
}
